package spring.library.LibraryProject.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import spring.library.LibraryProject.constant.constants;

import java.io.PrintWriter;

/**
 * 拦截器 可以对请求在被处理之前进行初步的判断筛选
 * 实现接口HandlerInterceptor
 */
@Component
public class loginInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(loginInterceptor.class);

    //在controller之前的操作 true放行 false阻止
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse res, Object handler) throws Exception {

        logger.info("-----preHandle 执行前-----");
        //拦截未登录
        if (!verifySession(request.getSession())) {
            logger.info("拦截的url = " + request.getRequestURI());

            //直接从定向到login 没有跳转到unLogin

            //res.setContentType("application/json;charset=utf-8");
//            res.setContentType("text/html");
//            res.setCharacterEncoding("UTF-8");
            res.setStatus(401);
            //res.sendRedirect("/library/unLogin.html");
            return false;
        }
        return true;
    }

    private boolean verifySession(HttpSession session) {
        logger.info("Session = " + session.toString());
        return session.getAttribute(constants.SESSION_USER_KEY) != null;
    }

    //在controller执行之后的操作
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("-----preHandle 执行后-----");

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

//    视图渲染完毕后执⾏，最后执⾏
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
